import BaseGroup from '@/components/js/BaseGroup'
import { COMPONENT_TYPES } from '@/common/const-wb'
import { MOBILE_WID_HEI } from '@/common/const-dif'
import { addEvent, removeEvent } from '@/plugins/dom'
import { EventBus } from '@/store/index'

export default class DragInRect extends BaseGroup {
  constructor() {
    super();
    //子类覆盖
    this.touchPosition = { touchX: 0, touchY: 0 };
    this.raduisR = parseInt(40 / MOBILE_WID_HEI.adaptiveScale);
    this.keyPoints = null;
    this.hiddenComps = [];
    this.hiddenIndexs = null;
    this.currentIndex = -1;
    this.svgItem = null;
    this.keyPointsLength = 0;
    this.defaultRaduis = 20;
    this.wIndexs = []
    this.wLengthList = []
    this.total = 0
    this.progress = 0
    this.isHalfEvent = true
  }

  start() {
    _.forEach(this.components, (component) => {
      if (component.cid == COMPONENT_TYPES.wb_svg_icon) {
        this.svgItem = component;
      } else if (component.conAttr.width < 50 && component.conAttr.height < 50) {
        this.hiddenComps.push(component);
        component.commonAttr.isVisible = false;
        this.raduisR = component.conAttr.width / 2 / MOBILE_WID_HEI.adaptiveScale;
      }
    })

    let isVisibles = this.item.interactionData.injectJsClassObj.isVisibles;
    if (isVisibles) {
      _.forEach(isVisibles, (id) => {
        let comp = _.find(this.hiddenComps, function (item) { return item.id == id });
        comp.commonAttr.isVisible = true;
      })
    }
    
    this.initHidden()
    this.progressEmit = this.item.interactionData.injectJsClassObj.progressEmit

    if (this.svgItem.commonAttr.isDrag) {
      this.onTouchStart = this.onTouchStart.bind(this);
      this.onTouchMove = this.onTouchMove.bind(this);
      this.onTouchEnd = this.onTouchEnd.bind(this);
      addEvent(document.documentElement, "touchstart", this.onTouchStart);
      addEvent(document.documentElement, "touchend", this.onTouchEnd);

      this.emitVivusProress = _.throttle((progress) => {
        EventBus.$emit("setVivusProress", progress);
      }, 50);
      const raduis = this.raduisR;
      const left = parseInt(this.item.conAttr.left / MOBILE_WID_HEI.adaptiveScale);
      const top = parseInt(this.item.conAttr.top / MOBILE_WID_HEI.adaptiveScale);
      this.keyPoints = [];
      this.wIndexs = this.item.interactionData.injectJsClassObj.wIndexs || [0, 2, 3, 5];
      _.sortBy(this.hiddenComps, item => Number(item.itemIndex))
      _.forEach(this.hiddenComps, (component, index) => {
        const itemLeft = parseInt(component.conAttr.left / MOBILE_WID_HEI.adaptiveScale);
        const itemTop = parseInt(component.conAttr.top / MOBILE_WID_HEI.adaptiveScale);
        this.keyPoints.push({ x: left + itemLeft + raduis, y: top + itemTop + raduis });
        if (this.wIndexs.indexOf(index) > -1) {
          this.wLengthList.push(parseInt(this.item.conAttr.width / MOBILE_WID_HEI.adaptiveScale / 2))
        } else {
          this.wLengthList.push(parseInt(this.item.conAttr.height / MOBILE_WID_HEI.adaptiveScale))
        }
      })
      this.hiddenIndexs = [];
      this.currentIndex = -1;
      this.keyPointsLength = this.keyPoints.length;
      this.total = _.sum(this.wLengthList.slice(0, this.wLengthList.length))
    }
  }

  onTouchStart(e) {
    const touchPosition = this.touchPosition;
    touchPosition.touchX = (e.touches ? e.touches[0].pageX : e.pageX);
    touchPosition.touchY = (e.touches ? e.touches[0].pageY : e.pageY);
    EventBus.$emit("resetVivus");
    let touch = {
      x: touchPosition.touchX,
      y: touchPosition.touchY,
    }
    if (this.computePointIsInCircle(touch, this.keyPoints[0])) {
      addEvent(document.documentElement, "touchmove", this.onTouchMove);
    }

    let jumpUrl = "svg-drag-" + this.item.index;
    let comType = "dragstart";
    let wModule = "drag";
    this.onPostStatics(e, { comType, wModule, jumpUrl });
  }

  onTouchMove(e) {
    let touchPosition = this.touchPosition;
    if (this.currentIndex != -1) {
      touchPosition.touchX = this.keyPoints[this.currentIndex].x;
      touchPosition.touchY = this.keyPoints[this.currentIndex].y;
    }
    const touchX = (e.touches ? e.touches[0].pageX : e.pageX);
    const touchY = (e.touches ? e.touches[0].pageY : e.pageY);

    const currentTouchPosition = { x: touchX, y: touchY };
    let isPush = false;
    _.forEach(this.keyPoints, (circle, index) => {
      //这个代码必须匹配index和length才能push，如0，0和1，1，保证第一个是起点位置
      if (this.computePointIsInCircle(currentTouchPosition, circle)) {
        if (this.hiddenIndexs.indexOf(index) == -1) {
          if (this.hiddenIndexs.length == index) {
            isPush = true
          } else {
            isPush = false
          }
          if (isPush) {
            this.hiddenIndexs.push(index);
            if (index > this.currentIndex) {
              this.currentIndex = index % this.keyPointsLength;
              // this.hiddenComps[this.currentIndex].commonAttr.isVisible = false;
              // this.hiddenComps[(this.currentIndex+1)%this.keyPointsLength].commonAttr.isVisible = true;
              touchPosition.touchX = this.keyPoints[this.currentIndex].x;
              touchPosition.touchY = this.keyPoints[this.currentIndex].y;
            }
          }
        }
      }
    })
    if (this.currentIndex != -1) {
      let pp = 0;
      if (this.wIndexs.indexOf(this.currentIndex) > -1) {
        pp = Math.abs(touchX - touchPosition.touchX)
      } else {
        pp = Math.abs(touchY - touchPosition.touchY)
      }
      let progress = 0
      if (this.currentIndex > 0) {
        progress = (pp + _.sum(this.wLengthList.slice(0, this.currentIndex))) / this.total
      } else {
        progress = pp / this.total
      }

      this.progress = progress
      this.emitVivusProress(progress);

      let hiddenCompIds, displayCompIds
      if(progress >= 0.98){
        progress = 1
        removeEvent(document.documentElement, "touchstart", this.onTouchStart);
        removeEvent(document.documentElement, "touchmove", this.onTouchMove);
        removeEvent(document.documentElement, "touchend", this.onTouchEnd);
        hiddenCompIds  = this.progressEmit[progress].hiddenCompIds
        displayCompIds = this.progressEmit[progress].displayCompIds
        EventBus.$emit("setVivusProress", progress);   
        let delayTime = this.item.interactionData && this.item.interactionData.injectJsClassObj.delayTime
        if(!delayTime) delayTime = 0.5;
        let svgItemId = this.svgItem.id;
        let itemIndex = this.svgItem.commonAttr.itemIndex;
        window.setTimeout(() => {
          console.log('执行')
          EventBus.$emit("itemClick", {id: svgItemId, index: itemIndex});
        }, delayTime*1000); 
      }else if(progress > 0.5 && this.isHalfEvent){
        this.isHalfEvent = false
        hiddenCompIds  = this.progressEmit['0.5'].hiddenCompIds
        displayCompIds = this.progressEmit['0.5'].displayCompIds
      }

      if(hiddenCompIds) {
        hiddenCompIds = hiddenCompIds.split(',')
        _.forEach(hiddenCompIds,id =>{
          let comp = this.componentMap[id]
          comp.commonAttr.isVisible = false;
        })
      }
      if(displayCompIds){
        displayCompIds = displayCompIds.split(',')
        _.forEach(displayCompIds,id =>{
          let comp = this.componentMap[id]
          comp.commonAttr.isVisible = true;
        })
      }
    }
  }
  onTouchEnd() {
    this.isHalfEvent = true
    this.currentIndex = -1;
    while (this.hiddenIndexs.length > 0) {
      this.hiddenIndexs.pop();
    }
    if (this.progress < 1) {
      EventBus.$emit("resetVivus");
      this.initHidden()
    }
    // _.forEach(this.hiddenComps, (comp) => {
    //   comp.commonAttr.isVisible = false;
    // })
    this.progress = 0
    removeEvent(document.documentElement, "touchmove", this.onTouchMove);
    // this.hiddenComps[0].commonAttr.isVisible = true;
  }

  computePointIsInCircle(p, circle) {
    //求点到圆心的距离，用到了勾股定理
    const offsetX = p.x - circle.x;
    const offsetY = p.y - circle.y;
    var dis = Math.sqrt(offsetX * offsetX + offsetY * offsetY);//Math.sqrt()求平方跟
    let raduisR = this.raduisR;
    if (raduisR < this.defaultRaduis) {
      raduisR = this.defaultRaduis;
    }
    if (dis <= raduisR) {
      return true;
    }
    return false;
  }

  initHidden(){
    // 初始化隐藏组件
    let initHiddenCompIds = this.item.interactionData.injectJsClassObj.initHiddenCompIds
    if (initHiddenCompIds) {
      initHiddenCompIds = initHiddenCompIds.split(',')
      _.forEach(initHiddenCompIds, id =>{
        let comp = this.componentMap[id]
        comp.commonAttr.isVisible = false;
      })
    }
  }

  destroy() {
    super.destroy();
    this.touchPosition = null;
    this.raduisR = 0;
    this.keyPoints = null;
    this.hiddenComps = null;
    this.hiddenIndexs = null;
    this.currentIndex = -1;
    this.progressCompId = 0;
    this.isShowProgress = false;
    this.showProgress = 0;
    if (this.svgItem.commonAttr.isDrag) {
      removeEvent(document.documentElement, "touchstart", this.onTouchStart);
      removeEvent(document.documentElement, "touchmove", this.onTouchMove);
      removeEvent(document.documentElement, "touchend", this.onTouchEnd);
      this.onTouchStart = null;
      this.onTouchMove = null;
      this.onTouchEnd = null;
    }
    this.svgItem = null;
  }
}
